<?php

/**
 * 生成供前端ajax或有router使用的uri，即去掉 'api' 和后台prefix.
 *
 * @param string $path 默认为当前请求的path
 * @param int    $slice 去掉uri后面的部分(-1为去掉一个)
 *
 * @return string
 */
function route_path($slice = 0, $path = ''): string
{
    if (empty($path)) {
        $path = app('request')->getPathInfo();
    }

    $segments = explode('/', trim($path, '/'));
    $segments = array_filter($segments);

    // 去掉api和admin prefix前缀
    foreach (['api', config('admin.prefix')] as $str) {
        if (($segments[0] ?? '') === $str) {
            array_shift($segments);
        }
    }

    if ($slice !== 0) {
        $segments = array_slice($segments, 0, $slice);
    }

    return '/'.implode('/', $segments);
}

/**
 * 把$path拼接成类似/api/admin/path路径
 *
 * @param $path
 *
 * @return string
 */
function full_request_path($path): string
{
    $segments = ['api', trim(config('admin.prefix'), '/'), trim($path, '/')];

    return '/'.implode('/', array_filter($segments));
}
